package com.nananren.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nananren.anno.ExceptionLogLog;
import com.nananren.anno.OperateLogLog;
import com.nananren.common.MyThreadLocal;
import com.nananren.common.Result;
import com.nananren.domain.Borrow;
import com.nananren.domain.User;
import com.nananren.service.UserService;
import com.nananren.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    // 添加用户
    @ExceptionLogLog
    @PostMapping
    @OperateLogLog
    public Result save(@RequestBody User user) throws Exception {
//        if (true) throw new Exception("我草了，出异常了!!");
        log.info("添加的用户信息为：{}", user.toString());
        // 条件构造器
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        userLambdaQueryWrapper.eq(User::getIsDeleted, 0);
        User userInDB = userService.getOne(userLambdaQueryWrapper);
        if (userInDB != null) {
            // 说明数据库中存在该用户，需要把isDeleted修改为1
            userInDB.setIsDeleted(1);
            userInDB.setStatus(user.getStatus());
            userInDB.setCreateTime(LocalDateTime.now());
            userInDB.setCreateUser(MyThreadLocal.getLocal());
            // 处理密码
            String password = "123456";
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            userInDB.setPassword(password);
            userService.updateById(userInDB);
            return Result.success("新增成功");
        }

        // 如果不在数据库里面，正常添加
        // 处理密码
        String password = "123456";
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);

        // 保存用户
        boolean flag = userService.save(user);
        return flag ? Result.success("添加成功") : Result.error("添加失败");
    }

    // 根据id查询用户
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询的用户id
        userLambdaQueryWrapper.eq(User::getId, id);

        // 查看用户是否被删除
        userLambdaQueryWrapper.eq(User::getIsDeleted, 1);

        // 查看用户状态
//        userLambdaQueryWrapper.eq(User::getStatus, 1);

        User user = userService.getOne(userLambdaQueryWrapper);
        return user != null ? Result.success(user) : Result.error("该用户不存在或已被禁用!!");
    }

    // 查询全部用户信息
    @GetMapping("/list")
    public Result list() throws Exception {
//        if (true) throw new Exception("我草了，出异常了!!");
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查看用户是否被删除
        userLambdaQueryWrapper.eq(User::getIsDeleted, 1);

        // 查看用户状态
        userLambdaQueryWrapper.eq(User::getStatus, 1);

        List<User> list = userService.list(userLambdaQueryWrapper);

        return list != null ? Result.success(list) : Result.error("暂无数据");
    }

    // 根据id修改用户信息
    @PutMapping
    @OperateLogLog
    public Result updateById(@RequestBody User user) throws Exception {
//        if (true) throw new Exception("我草了，出异常了!!");
        // 处理密码
//        String password = user.getPassword();
//        password = DigestUtils.md5DigestAsHex(password.getBytes());
//        user.setPassword(password);
        // 修改数据
        userService.updateById(user);

        return Result.success("修改成功");
    }

    // 根据id删除用户
    @DeleteMapping("/{id}")
    @OperateLogLog
    public Result deleteById(@PathVariable Long id) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getId, id);
        userLambdaQueryWrapper.eq(User::getIsDeleted, 1);
        User user = userService.getOne(userLambdaQueryWrapper);
        if (user != null) {
            user.setIsDeleted(0);
            userService.updateById(user);
            return Result.success("删除成功");
        }

        return Result.error("用户信息不存在!!");

    }

    // 条件分页查询
    @GetMapping("/page")
    public Result page(int page, int pageSize, String username, Long status,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime begin,
                       @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime end) {
        log.info("page：{}, pageSize: {}, username: {}, status: {}, begin: {}, end: {}", page, pageSize, username,
                status, begin, end);
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        Page<User> userPage = new Page(page, pageSize);

        // 根据name模糊查询
        userLambdaQueryWrapper.like(username != null && username != "", User::getUsername, username);

        // 判断是否被删除
        userLambdaQueryWrapper.eq(User::getIsDeleted, 1);

        // begin等于null，end不等于null，查询borrow_time小于等于end的所有数据
        userLambdaQueryWrapper.le(begin == null && end != null, User::getCreateTime, end);
        // begin不等于null，end等于null，查询borrow_time大于等于begin的所有数据
        userLambdaQueryWrapper.ge(begin != null && end == null, User::getCreateTime, begin);
        // begin和end都不等于null，查询borrow_time大于等于begin并小于等于end的所有数据
        userLambdaQueryWrapper.between(begin != null && end != null, User::getCreateTime, begin, end);

        // 状态
        userLambdaQueryWrapper.eq(status != null, User::getStatus, status);

        // 排序
        userLambdaQueryWrapper.orderByDesc(User::getUpdateTime);
        userService.page(userPage, userLambdaQueryWrapper);
        log.info("userPage.getTotal的值为：{}", userPage.getTotal());

        // 判断total总数是否为0
        return userPage.getTotal() != 0 ? Result.success(userPage) : Result.error("暂无数据");

    }

    // 批量禁用用户
    @PostMapping("/status/0")
    @OperateLogLog
    public Result stop(@RequestParam("ids") List<Long> ids) {
        log.info("要启用的id为：{}", ids);
        if (ids.size() == 0) {
            return Result.error("请输入正确的数据");
        }

        // 用来存储根据id查询的用户存在
        List<User> list = new ArrayList<>();
        // 遍历集合，判断根据id查询出来的用户是否存在
        // 存在：修改isDeleted为0，并添加到list
        // 不存在：数据有误，返回数据异常结果
        for (Long id : ids) {
            User user = userService.getById(id);
            if ( user == null ) {
                return Result.error("数据异常");
            }
            user.setStatus(0);
            list.add(user);
        }

        userService.updateBatchById(list);
        return Result.success("操作成功");
    }

    // 批量启用用户
    @PostMapping("/status/1")
    @OperateLogLog
    public Result start(@RequestParam("ids") List<Long> ids) {
        log.info("要启用的id为：{}", ids);
        if (ids.size() == 0) {
            return Result.error("请输入正确的数据");
        }

        // 用来存储根据id查询的用户存在
        List<User> list = new ArrayList<>();
        // 遍历集合，判断根据id查询出来的用户是否存在
        // 存在：修改isDeleted为0，并添加到list
        // 不存在：数据有误，返回数据异常结果
        for (Long id : ids) {
            User user = userService.getById(id);
            if ( user == null ) {
                return Result.error("数据异常");
            }
            user.setStatus(1);
            list.add(user);
        }

        userService.updateBatchById(list);
        return Result.success("操作成功");
    }

    // 禁用单个员工
    @PostMapping("/status/single/0")
    @OperateLogLog
    public Result stopSingle(@RequestBody User user) {
        User userInDB = userService.getById(user.getId());
        if (userInDB == null) {
            return Result.error("当前用户不存在!");
        }

        if (userInDB.getStatus() == 0) {
            return Result.error("当前员工已被禁用!");
        }

        userInDB.setStatus(0);
        boolean flag = userService.updateById(userInDB);
        return flag ? Result.success("已禁用该员工") : Result.error("禁用失败");
    }

    // 启用单个员工
    @PostMapping("/status/single/1")
    @OperateLogLog
    public Result startSingle(@RequestBody User user) {
        User userInDB = userService.getById(user.getId());
        if (userInDB == null) {
            return Result.error("当前用户不存在!");
        }

        if (userInDB.getStatus() == 1) {
            return Result.error("当前员工已被禁用!");
        }

        userInDB.setStatus(1);
        boolean flag = userService.updateById(userInDB);
        return flag ? Result.success("已禁用该员工") : Result.error("禁用失败");
    }

    // 批量删除用户
    @PutMapping("/isDeleted/0")
    @OperateLogLog
    public Result deleteByIds(@RequestParam("ids") List<Long> ids) {
        log.info("批量删除用户，ids为{}", ids);
        // 条件构造器
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getIsDeleted, 1);
        userLambdaQueryWrapper.in(ids.size() != 0,  User::getId, ids);
        List<User> list = userService.list(userLambdaQueryWrapper);
        // 如果相等，说明传递的id所对应的用户都存在
        if (ids.size() == list.size()) {
            // 利用Stream流将每个元素的isDeleted设置为0
            list = list.stream().map(item -> {
                item.setIsDeleted(0);
                return item;
            }).collect(Collectors.toList());
            // 批量删除用户
            userService.updateBatchById(list);
            return Result.success("删除成功");
        }

        return Result.error("当前用户不存在!!");
    }

    // 用户登录
    @PostMapping("/login")
    @OperateLogLog
    public Result login(@RequestBody User user) {
        log.info("用户登录，用户信息为：{}", user.toString());
        // 处理密码
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        // 根据username和password在数据空中查找该用户
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, user.getUsername());
        userLambdaQueryWrapper.eq(User::getPassword, password);
        // 查询得到的用户
        User userInDB = userService.getOne(userLambdaQueryWrapper);
        // 如果不存在
        if (userInDB == null) {
            return Result.error("当前用户不存在");
        }
        // 如果存在，设置token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", userInDB.getId());
        claims.put("username", userInDB.getUsername());
        String jwt = JwtUtils.getJwt(claims);
        return Result.success("登陆成功", jwt);

    }
}
